/**
 * 颜色值校验的结果
 */
export interface ColorValid {
  valid: boolean
  color: string
}

/**
 * 颜色校验
 * @param color 颜色值
 */
export function colorValidator(color: string) {
  color = color.toUpperCase().replace(/\s+/g, '')
  const result: ColorValid = {
    valid: false,
    color: color,
  }
  if (/^\#([0-9A-F]{8}|[0-9A-F]{6}|[0-9A-F]{3})$/.test(color)) {
    result.valid = true
  } else if (/^RGB\(\d{1,3},\d{1,3},\d{1,3}\)$/.test(color) || /^RGBA\(\d{1,3},\d{1,3},\d{1,3},([01]|0?\.\d+)\)$/.test(color)) {
    const [r, g, b, a] = (color.match(/\d+/g) as [string, string, string, string?]).map(Number)
    result.valid = true
    result.color = RGBAToHEX(r, g, b, isNaN(a) ? 1 : a)
  }
  return result
}

/**
 * RGBA 转 HEX
 * @param r RGBA 的 R
 * @param g RGBA 的 G
 * @param b RGBA 的 B
 * @param a RGBA 的 A
 */
export function RGBAToHEX(r: number, g: number, b: number, a: number = 1) {
  const hex = `#${((1 << 24) + r * (1 << 16) + g * (1 << 8) + b).toString(16).slice(1).toUpperCase()}`
  return a === 1 ? hex : `${hex}${a.toString(16).toUpperCase().slice(2, 4) || '00'}`
}
